using System;
using Microsoft.SPOT;
using System.IO.Ports;
using System.Text;

namespace Netduino4Fun.DesktopAssistant.Netduino.Communication
{
    public class SerialConnection : Connection
    {
        SerialPort serialPort;

        public SerialConnection()
        {
            this.serialPort = new SerialPort(Configuration.SerialPort.PortName,
                                                Configuration.SerialPort.BaudRate, Configuration.SerialPort.Parity,
                                                Configuration.SerialPort.DataBits, Configuration.SerialPort.StopBits);
            this.serialPort.Handshake = Configuration.SerialPort.Handshake;
            this.serialPort.ReadTimeout = Configuration.SerialPort.ReadTimeout;
            this.serialPort.WriteTimeout = Configuration.SerialPort.WriteTimeout;
            this.serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
        }

        void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] buffer = new byte[this.serialPort.BytesToRead];
            int count = this.serialPort.Read(buffer, 0, buffer.Length);

            char[] chars = Encoding.UTF8.GetChars(buffer);
            Read(new string(chars));
        }

        public override void Open()
        {
            this.serialPort.Open();
        }

        protected override void Write(string data)
        {
            if (!this.serialPort.IsOpen)
                return;

            byte[] buffer = Encoding.UTF8.GetBytes(data);
            this.serialPort.Write(buffer, 0, buffer.Length);
        }
    }
}
